import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-11
 * Time: 8:10
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    //UDP本身不保存对端的信息, 就自己的代码中保存一下
    private String serverIP;
    private int serverPort;
    public UdpEchoClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP; //指定发送服务器的目的IP和目的端口
        this.serverPort = serverPort;
        //这里不填固定端口, 操作系统会长随机分配一个空闲端口
        socket = new DatagramSocket(); //客户端的端口号不能像服务器那样固定, 因为客户端很多会产生端口竞争, 这个时候我们找空闲的端口使用就行了
    }
    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.从控制台读取用户输入的数据
            System.out.println("请输入要发送的内容:");
            if(!scanner.hasNext()){
                break;
            }
            String request = scanner.next();
            //2.构造请求数据包, 把数据包发送给服务器
            //构造过程中不光要构造载荷, 还要设置服务器的IP和端口号
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            //3.发送数据包
            socket.send(requestPacket);
            //4.接受服务器的响应数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //5.从服务器读取的数据进行解析(二进制数据反序列化, 打印出来)
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("123.60.175.228", 8080);
        client.start();
    }
}
